<template>
  <div class="app-container home">
    <el-card>
      <div class="search">
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="68px"
          style="float: left"
        >
          <el-form-item
            label="时间"
            prop="detectionTime"
            style="margin-bottom: 0"
          >
            <el-date-picker
              v-model="queryParams.detectionTimes"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 0">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
        <div class="flex" style="flex: 1; margin-left: 5%">
          <div class="check flex">
            应检人数：<span>{{ dataInfo.renshu }}</span> 人
          </div>
          <div
            class="check flex"
            style="background-color: rgba(99, 149, 250, 1); margin-left: 20px"
          >
            已检人次：<span>{{ dataInfo.renci }}</span> 次
          </div>
        </div>
        <div>
          <el-button
            type="primary"
            v-if="stateBtn"
            @click="handleClickPopulation"
            >重点人群信息</el-button
          >
          <el-button type="warning" @click="handleClickSenior"
            >高级搜索</el-button
          >
        </div>
      </div>
    </el-card>
    <div>
      <el-card style="margin-top: 40px">
        <div class="echarts-wrapper" style="clear: both">
          <div
            v-loading="JSON.stringify(letBieInfo) === '{}'"
            class="inner"
            style="margin-right: 7%"
          >
            <Echarts
              :info="letBieInfo"
              idName="leibie"
              class="charts"
              @handleClickLine="handleNext"
            ></Echarts>
          </div>
          <div v-loading="JSON.stringify(letBieInfo) === '{}'" class="inner">
            <Echarts
              :info="departmentInfo"
              idName="department"
              @handleClickLine="handleNext"
              class="charts"
            ></Echarts>
          </div>
        </div>
      </el-card>
      <el-card style="margin-top: 40px">
        <div class="table-title">所有类别</div>
        <div
          class="echarts-wrapper leibie"
          style="clear: both"
          v-if="chartList.length > 0"
        >
          <div v-for="(item, index) in chartList" :key="index" class="inner">
            <Echarts
              :info="item"
              :idName="'chart-' + index"
              @handleClickLine="handleNext"
              class="charts"
            ></Echarts>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 高级搜索 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      append-to-body
      width="1000px"
    >
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="时间" prop="detectionTime">
          <el-date-picker
            v-model="dialogForm.date"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item label="类别" prop="detectionCycleId">
          <el-select
            v-model="dialogForm.detectionCycleId"
            filterable
            placeholder="请选择类别"
          >
            <el-option
              v-for="item in category"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-bottom: 0">
          <el-button type="primary" icon="el-icon-search" @click="handleSearch"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
      <div ref="cake"></div>
    </el-dialog>
    <!-- 图表下一级 -->
    <el-dialog
      :visible.sync="chartDialog"
      append-to-body
      width="1000px"
      :destroy-on-close="true"
    >
      <div class="inner">
        <div
          ref="chartDialog"
          id="chartDialog"
          class="box"
          style="width: 80%; height: 75%"
        />
      </div>
    </el-dialog>
    <!-- 重点人群信息 -->
    <el-dialog
      :visible.sync="populationDialog"
      append-to-body
      width="1000px"
      :destroy-on-close="true"
      title="重点人群信息"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="inner" style="padding: 0 40px">
        <Echarts
          :info="populationInfo"
          idName="populationDialog"
          class="charts"
        ></Echarts>
        <div class="table-title">未完成检测的重点人群信息</div>
        <el-table :data="populationList" border>
          <el-table-column
            label="类别"
            align="center"
            prop="detectioncycleName"
          >
            <template slot-scope="{ row }">
              {{
                (row.detectionCycleList &&
                  row.detectionCycleList.length > 0 &&
                  row.detectionCycleList[0].categoryName) ||
                ""
              }}
            </template>
          </el-table-column>
          <el-table-column label="所属部门" align="center" prop="deptName" />
          <el-table-column
            label="姓名"
            align="center"
            prop="personName"
            width="100"
          />
          <el-table-column
            label="联系方式"
            align="center"
            prop="phoneNumber"
            width="150"
          />
        </el-table>
        <pagination
          v-show="populationTotal > 0"
          :total="populationTotal"
          :page.sync="populationParams.pageNum"
          :limit.sync="populationParams.pageSize"
          @pagination="getPopulation"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  getLeiBie,
  statistics,
  zhongdian,
  getHnagYeFenLei,
  gaoji,
  leibie,
  nextData,
  population,
} from "@/api/echarts.js";
let timer = 1;
import { categorychargelist } from "@/api/control/person";
import Echarts from "@/components/Echarts/index";
export default {
  name: "Index",
  data() {
    return {
      // 搜索form
      queryParams: {
        detectionTimes: null,
      },
      mychart: "",
      title: "详细信息",
      dataInfo: {
        renci: 0,
        renshu: 0,
      },
      tableList: [],
      stats: 0,
      loading: false,
      dialogVisible: false,
      stateBtn: 0,
      dialogForm: {
        date: null,
        detectionCycleId: null,
      },
      category: [],
      chartList: [],
      chartDialog: false,
      letBieInfo: {},
      departmentInfo: {},
      timer: 1,
      populationDialog: false,
      populationInfo: {},
      populationList: [],
      populationParams: {
        pageNum: 1,
        pageSize: 10,
        falg: 1,
      },
      populationTotal: 0,
    };
  },
  watch: {
    timer(val) {
      if (val === 0) {
        setTimeout(() => {
          this.timer = 1;
        });
      }
    },
  },
  components: {
    Echarts,
  },
  created() {
    const intervalTime = 24 * 60 * 60 * 1000 * 2;
    const currentTime = new Date().getTime();
    const starTime = new Date(currentTime - intervalTime);
    this.queryParams.detectionTimes = [
      this.parseTime(starTime),
      this.parseTime(currentTime),
    ];
    this.getStatistics();
    this.getZhongDian();
  },
  mounted() {
    this.getLeiBie();
    this.getHnagYeFenLei();
    this.getSuoYouLeiBie();
  },
  methods: {
    getHnagYeFenLei() {
      getHnagYeFenLei().then((res) => {
        if (res.code == 200) {
          this.departmentInfo = {
            data: res.data,
            cursor: "pointer",
            title: "部门分类",
          };
        }
        this.loading = false;
      });
    },
    // 类别下拉
    categorychargeList() {
      categorychargelist().then((res) => {
        this.category = res.data;
      });
    },
    // 所有类别图表
    getSuoYouLeiBie() {
      leibie().then((res) => {
        res.data.forEach((item, index) => {
          this.chartList.push({});
          item.data = item.value;
          item.title = item.name;
        });
        this.$nextTick(() => {
          this.chartList = res.data;
        });
      });
    },
    // 统计
    getStatistics() {
      statistics({
        starTime:
          this.queryParams.detectionTimes && this.queryParams.detectionTimes[0],
        entTime:
          this.queryParams.detectionTimes && this.queryParams.detectionTimes[1],
      }).then((res) => {
        this.dataInfo = res.data;
      });
    },
    // 重点人群信息按钮
    getZhongDian() {
      zhongdian().then((res) => {
        this.stateBtn = res.state;
      });
    },
    // 时间筛选
    handleQuery() {
      this.getStatistics();
    },
    // 重点人群分类
    getLeiBie() {
      getLeiBie()
        .then((res) => {
          if (res.cod == 200) {
            this.letBieInfo = {
              data: res.data,
              cursor: "auto",
              title: "重点人群分类",
            };
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 图表下一级
    handleNext(data) {
      console.log("next");
      if (this.timer === 0) return;
      this.timer = 0;
      nextData(data).then((res) => {
        if (res.code == 200) {
          this.chartDialog = true;
          this.$nextTick(() => {
            let info = res.data;
            if (Array.isArray(info)) {
              info = info[0].value;
            }
            this.initCharts(
              info,
              this.$refs.chartDialog,
              "pointer",
              data.value
            );
          });
        }
      });
    },
    // 高级搜索
    handleClickSenior() {
      this.dialogVisible = true;
      this.title = "高级搜索";
      this.categorychargeList();
      this.getGaoJi();
    },
    handleSearch() {
      // const data = [
      //   { value: 1048, name: "Search Engine" },
      //   { value: 735, name: "Direct" },
      //   { value: 580, name: "Email" },
      //   { value: 484, name: "Union Ads" },
      //   { value: 300, name: "Video Ads" },
      // ];
      // this.initCakeCharts({tubiao: data}, this.$refs.cake);
      this.getGaoJi();
    },
    // 高级搜索数据
    getGaoJi() {
      console.log(this.dialogForm.date)
      
      gaoji({
        detectionCycleId: this.dialogForm.detectionCycleId,
        starTime: this.dialogForm.date && this.parseTime(this.dialogForm.date[0]),
        endTime: this.dialogForm.date && this.parseTime(this.dialogForm.date[1]),
      }).then((res) => {
        const info = res.data.detectionCycleTimeVo;
        if (info) {
          this.dialogForm.date = [
            new Date(info.starTime),
            new Date(info.endTime),
          ];
          this.dialogForm.detectionCycleId = info.detectionCycleId;
        }
        this.$nextTick(() => {
          this.initCakeCharts(res.data, this.$refs.cake);
        });
      });
    },
    // 重点人群信息
    handleClickPopulation() {
      this.populationDialog = true;
      this.$nextTick(() => {
        this.populationInfo = JSON.parse(JSON.stringify(this.letBieInfo));
      });
      this.getPopulation();
    },
    // 重点人群信息-表格
    getPopulation() {
      population(this.populationParams).then((res) => {
        this.populationList = res.rows;
        this.populationTotal = res.total;
      });
    },
    // 柱状图
    initCharts(data, dom, cursor, title) {
      /**
       * data 图表数据
       * dom  图表元素
       * cursor  是否有点击事件
       * title  标题
       */
      echarts.init(dom).setOption(
        {
          title: {
            text: title,
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          legend: {
            show: false,
          },
          grid: {
            left: "0%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: [
            {
              type: "value",
              boundaryGap: [0, 0.01],
            },
          ],
          yAxis: {
            type: "category",
            inverse: true,
            data: data.categories,
            axisLabel: {
              //坐标轴刻度标签的相关设置。
              formatter: function (params) {
                var newParamsName = ""; // 最终拼接成的字符串
                var paramsNameNumber = params.length; // 实际标签的个数
                var provideNumber = 8; // 每行能显示的字的个数
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话，需要显示几行，向上取整
                /**
                 * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
                 */
                // 条件等同于rowNumber>1
                if (paramsNameNumber > provideNumber) {
                  /** 循环每一行,p表示行 */
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = ""; // 表示每一次截取的字符串
                    var start = p * provideNumber; // 开始截取的位置
                    var end = start + provideNumber; // 结束截取的位置
                    // 此处特殊处理最后一行的索引值
                    if (p == rowNumber - 1) {
                      // 最后一次不换行
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      // 每一次拼接字符串并换行
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr; // 最终拼成的字符串
                  }
                } else {
                  // 将旧标签的值赋给新标签
                  newParamsName = params;
                }
                //将最终的字符串返回
                return newParamsName;
              },
            },
          },
          series: [
            {
              name: data.series[0].name,
              type: "bar",
              data: data.series[0].data,
              itemStyle: {
                color: "rgba(84,112,198,1)",
              },
              cursor: cursor || "pointer",
            },
            {
              name: data.series[1].name,
              type: "bar",
              data: data.series[1].data,
              itemStyle: {
                color: "rgba(238,102,102,1)",
              },
              cursor: cursor || "pointer",
            },
          ],
        },
        true
      );
      let myChart = echarts.init(dom);
      myChart.off("click");
      // myChart.clear()
      this.autoHeight = data.categories.length * 55 + 50;
      if (this.autoHeight < 200) {
        this.autoHeight = 200;
      }
      // if (this.autoHeight < 500) {
      myChart.getDom().parentNode.style.height = this.autoHeight + "px";
      // }
      myChart.getDom().style.height = this.autoHeight + "px";
      myChart.resize();
      if (cursor === "auto") return;
      myChart.getZr().off('click')
      myChart.getZr().on("click", (params) => {
        const pointInPixel = [params.offsetX, params.offsetY];
        if (myChart.containPixel("grid", pointInPixel)) {
          let xIndex = myChart.convertFromPixel({ seriesIndex: 0 }, [
            params.offsetX,
            params.offsetY,
          ]);
          console.log(data)
          this.handleNext(data.categories[parseInt(xIndex[1])]);
        }
      });
    },
    // 饼图
    initCakeCharts(res, dom, title) {
      const data = res.tubiao;
      echarts.init(dom).setOption(
        {
          tooltip: {
            trigger: "item",
          },
          legend: {
            orient: "vertical",
            left: "left",
            top: "10%",
            formatter: function (name) {
              var total = 0;
              var tarValue;
              for (var i = 0; i < data.length; i++) {
                total += data[i].value;
                if (data[i].name == name) {
                  tarValue = data[i].value;
                }
              }
              var v = tarValue;
              return `${name}  ${v}人次`;
            },
          },
          series: {
            name: "统计",
            type: "pie",
            radius: ["40%", "70%"],
            label: {
              show: true,
              position: "center",
              formatter: function () {
                return "完成率\r\n" + res.wanclv + "%";
              },
              fontSize: 16,
            },
            data: data,
          },
        },
        true
      );
      let myChart = echarts.init(dom);
      myChart.off("click");
      this.autoHeight = data.length * 70 + 50;
      if (this.autoHeight < 200) {
        this.autoHeight = 200;
      }
      this.autoHeight = 325;
      myChart.getDom().style.height = this.autoHeight + "px";
      myChart.resize();
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  .echarts-wrapper {
    display: flex;
    margin-top: 20px;
    .inner {
      position: relative;
      flex: 1;
      overflow-y: auto;
      margin-bottom: 20px;
      .box {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
      }
    }
  }
  .leibie {
    max-height: 400px;
    overflow-y: auto;
    flex-wrap: wrap;
    .inner {
      width: 33.33%;
      flex: none;
    }
  }
  .inner {
    max-height: 500px;
  }
}
.table-title {
  font-size: 20px;
  margin-bottom: 20px;
}
.table-box {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
}
.echarts-wrapper {
  padding-left: 30px;
}
.jiance {
  margin-top: 10px;
}
.search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .check {
    padding: 0 20px;
    height: 52px;
    background: inherit;
    background-color: rgba(2, 167, 240, 1);
    border: none;
    border-radius: 5px;
    color: #fff;
    font-size: 14px;
    justify-content: center;
    span {
      font-size: 28px;
    }
  }
}
.flex {
  display: flex;
  align-items: center;
}
.inner {
  &::-webkit-scrollbar {
    width: 8px;
  }
  &::-webkit-scrollbar-track {
    border-radius: 4px;
    background-color: rgba(241, 241, 241, 1);
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: rgba(193, 193, 193, 1);
  }
  max-height: 500px;
  overflow-y: auto;
}
</style>
<style></style>
